﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Mvc;
using System.Web.Routing;
using Web.Utility;
using DddCms.Domain.Factory;
using DddCms.Domain.Utility;
using DddCms.Domain.Repository;
using Microsoft.Practices.Unity;
using DddCms.Presentation.Utility;
using DddCms.Infrastructure.Repository;
using DddCms.Presentation.Controllers;
using DddCms.Areas.Presentation.Controllers;
using Web.Controllers;
using System.Data.Entity;
using DddCms.Infrastructure.Logging;

namespace DddCms.Presentation
{
    public class Global : HttpApplication
    {
        /// <summary>
        /// Application_s the start.
        /// </summary>
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            //Set the Dependency Resolver ASP.Net MVC

            UnityDependencyResolver container = new UnityDependencyResolver();
            container.unityContainer.RegisterType<IController, UserWidgetController>("userwidget");
            container.unityContainer.RegisterType<IController, UserController>("user");
            container.unityContainer.RegisterType<IController, MenuController>("menu");

            DependencyResolver.SetResolver(container);
           
            // Create database if not exist
            Database.SetInitializer<DataContext>(container.unityContainer.BuildUp(new DatabaseInitializer()));
            ControllerBuilder.Current.SetControllerFactory(new UnityControllerFactory(container.unityContainer));


            ModelMetadataProviders.Current = new HelperModelMetadataProvider();
        }

        /// <summary>
        /// Registers the global filters.
        /// </summary>
        /// <param name="filters">The filters.</param>
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        /// <summary>
        /// Registers the routes.
        /// </summary>
        /// <param name="routes">The routes.</param>
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("favicon.ico");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );
        }
    }
}
